

import 'package:basic_common/common_exports.dart';
import 'package:basic_common/global_getx.dart';
import 'package:basic_modle/upload_data.dart';
import 'package:basic_services/model/server_fat_detail_data.dart';
import 'package:basic_widgets/bottom_img_picker.dart';

class ServerDetailController extends GetxController {
  final List basicList = [
    {"attr": "姓名", "value": ""},
    {"attr": "身份证号", "value": ""},
    {"attr": "性别", "value": ""},
    {"attr": "年龄", "value": ""},
    {"attr": "联系电话", "value": ""},
    {"attr": "现居地", "value": ""}
  ];

  final List serverList = [
    {"attr": "服务机构", "value": ""},
    {"attr": "服务团队", "value": ""},
    {"attr": "服务医生", "value": ""},
    {"attr": "服务包", "value": ""},
    {"attr": "服务项目", "value": ""}
  ];



  final mserviceInfo = ServiceInfo().obs;
  final mpatientInfo = PatientInfo().obs;

  final srList = <SriList?>[].obs;

  final String status = '0';
  final cellEdits = <Widget>[].obs;
  final armValue = '1'.obs;
  final sugarValue = '1'.obs;

  // 详情信息
  final pNo = ''.obs;

  final tNo = ''.obs;
  final serviceId = ''.obs;

  final dNo = ''.obs;

  final cId = ''.obs;
  final serverStatus = ''.obs;
  final stausStr = ''.obs;

// 返回值动态
  final resultData = <String, dynamic>{}.obs;
  //// 添加服务项目 列表

  List<Map<String, dynamic>> addServerList = [
    {"name": "收缩压\n(高压)", "value": "", "unit": "mmHg"},
    {"name": "舒张压\n(低压)", "value": "", "unit": "mmHg"},
    {"name": "心率", "value": "", "unit": "次/分钟"}
  ];

  //TextEditingController数组
  List<TextEditingController> inputEditingControllers =
      <TextEditingController>[];

  TextEditingController estimateController = TextEditingController();

  TextEditingController sugarInputController = TextEditingController();
  TextEditingController elaInputController = TextEditingController();

  TextEditingController weightController = TextEditingController();
  TextEditingController evaController = TextEditingController();
 final sList=[].obs;
  // 血脂
  List<Map<String, dynamic>> addFatList = [
    {"name": "测量结果", "value": "", "unit": "mmol/L"},
    {"name": "TC", "value": "", "unit": "mmol/L"},
    {"name": "TG", "value": "", "unit": "mmol/L"},
    {"name": "CE", "value": "", "unit": "mmol/L"},
    {"name": "HDL-C", "value": "", "unit": "mmol/L"},
    {"name": "LDL-C-C", "value": "", "unit": "mmol/L"}
  ];
  //TextEditingController数组
  List<TextEditingController> fatInputControllers = <TextEditingController>[];
  //血脂的组件库
  final fatCellEdits = <Widget>[].obs;
  TextEditingController fatelaInputController = TextEditingController();

  // 其他数据添加库

  TextEditingController otherElaController = TextEditingController(); //评估
  TextEditingController OtherIntroController = TextEditingController(); //测量说明

  // 其他数据添加 图片地址
  final otherImgUrl = ''.obs;

// 常用添加数据类型
  List<String> normalTypeList = [
    "bloodpressure",
    "bloodsugar",
    "weight",
    "bloodfat"
  ];
  final addType = "other".obs; //添加数据的类型

  final nameEnStr = "".obs; //

  /// 获取排班服务详情
  void getServerDetail(
      {required String pNo,
      required String tNo,
      required String serviceId,
      required String dNo,
      required String cId}) async {
    HttpData res = await ApiService().serverDetail(data: {
      "patientNo": pNo,
      "servicePackageId": serviceId,
      "teamNo": tNo,
      "doctorNo": dNo,
      "checkId": cId
    });
    if (res.code == 1) {
      String nameEn = res.data['serviceInfo']['nameEn'];
      if (!normalTypeList.contains(nameEn)) {
        addType.value = "other";
      } else {
        addType.value = nameEn;
      }
      nameEnStr.value = nameEn;
     sList.value = res.data['sriList'];
      if (  sList.value.isNotEmpty) {
        resultData.value = res.data;
      }

      mpatientInfo.value = PatientInfo.fromJson(res.data['patientInfo']);
      mserviceInfo.value = ServiceInfo.fromJson(res.data['serviceInfo']);

      update(['serverDetail']);

      PatientInfo pInfo = mpatientInfo.value;
      updateInfo(0, pInfo.patientName ?? '');
      updateInfo(1, pInfo.idCardNo ?? '');
      updateInfo(2, pInfo.gender == '1' ? '男' : '女');
      updateInfo(3, '${pInfo.patientAge ?? '0'}');
      updateInfo(4, pInfo.phone!);
      updateInfo(5, pInfo.address!);

      ServiceInfo sInfo = mserviceInfo.value;
      serverStatus.value = sInfo!.servicestatus!;
      updateServerInfo(0, sInfo.hospname!);
      updateServerInfo(1, sInfo.teamname!);
      updateServerInfo(2, sInfo.doctornick!);
      updateServerInfo(3, sInfo.packagename!);
      updateServerInfo(4, sInfo.itemname!);
      update(['serverDetail']);
    }
  }

  updateInfo(int index, String value) {
    basicList[index]['value'] = value;
  }

  updateServerInfo(int index, String value) {
    serverList[index]['value'] = value;
  }



  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();
    pNo.value = Get.arguments['patientNo'];
    tNo.value = Get.arguments['teamNo'];
    serviceId.value = Get.arguments['servicePackageId'];
    dNo.value = Get.arguments['doctorNo'];
    cId.value = Get.arguments['checkId'];
    getServerDetail(
        pNo: pNo.value,
        tNo: tNo.value,
        dNo: dNo.value,
        cId: cId.value,
        serviceId: serviceId.value);
  }

  /// 添加血压数据
  void addPressureData() async {
    String pId = mpatientInfo.value.id.toString();
    String arm = armValue.value;
    String high = inputEditingControllers[0].text;
    String low = inputEditingControllers[1].text;
    String heart = inputEditingControllers[2].text;
    String mId = mserviceInfo.value.medicalAdviceId.toString();
    String eva = estimateController.text;
    String pUserId = mpatientInfo.value.consumerId.toString();
    HttpData res = await ApiService().addServerPressData(data: {
      "patientInfoId": pId,
      "armFlag": arm,
      "systolicPressure": high,
      "diastolicPressure": low,
      "heartRate": heart,
      "medicalAdviceId": mId,
      "evaluate": eva,
      "patientUserId": pUserId
    });
    if (res.code == 1 && res.data['result'] == 1) {
      ToastUtils.toast("添加成功");
      updateServerStatus();
      navToConsumable();
    } else {
      ToastUtils.toast("${res.msg}");
    }
  }

  /// 添加血糖
  void addSugarData(
      {required String checkValue, required String evaValue}) async {
    String uId = mpatientInfo.value.consumerId!.toString();
    String pId = mpatientInfo.value.id.toString();
    String sugarType = sugarValue.value;
    String mId = mserviceInfo.value.medicalAdviceId.toString();
    if (uId.isEmpty || pId.isEmpty) {
      ToastUtils.toast("用户Id不能为空");
      return;
    }
    if (checkValue.isEmpty) {
      ToastUtils.toast("血糖值不能为空");
      return;
    }

    HttpData res = await ApiService().addServerSugarData(data: {
      "patientUserId": uId,
      "patientInfoId": pId,
      "medicalAdviceId": mId,
      "mealsFlag": sugarType,
      "value": checkValue,
      "evaluate": evaValue
    });
    if (res.code == 1) {
      navToConsumable();
    } else {
      ToastUtils.toast("${res.msg}");
    }
  }

  /// 添加体重数据
  void addWeightData(
      {required String weightValue, required String evaValue}) async {
    String uId = mpatientInfo.value.consumerId!.toString();
    String pId = mpatientInfo.value.id.toString();
    String mId = mserviceInfo.value.medicalAdviceId.toString();
    if (uId.isEmpty || pId.isEmpty) {
      ToastUtils.toast("用户Id不能为空");
      return;
    }
    if (weightValue.isEmpty) {
      ToastUtils.toast("体重值不能为空");
      return;
    }

    HttpData res = await ApiService().addServerWeightData(data: {
      "patientUserId": uId,
      "patientInfoId": pId,
      "medicalAdviceId": mId,
      "value": weightValue,
      "evaluate": evaValue
    });
    if (res.code == 1) {
      navToConsumable();
    } else {
      ToastUtils.toast("${res.msg}");
    }
  }

  /// 添加血脂
  void addFatData({required String evaValue}) async {
    String uId = mpatientInfo.value.consumerId!.toString();
    String pId = mpatientInfo.value.id.toString();
    String mId = mserviceInfo.value.medicalAdviceId.toString();
    if (uId.isEmpty || pId.isEmpty) {
      ToastUtils.toast("用户Id不能为空");
      return;
    }
    String resultVal = fatInputControllers[0].text;
    String tcVal = fatInputControllers[1].text;
    String tgVal = fatInputControllers[2].text;
    String ceVal = fatInputControllers[3].text;
    String hdlVal = fatInputControllers[4].text;
    String ldlVal = fatInputControllers[5].text;
    if (resultVal.isEmpty ||
        tcVal.isEmpty ||
        tgVal.isEmpty ||
        ceVal.isEmpty ||
        hdlVal.isEmpty ||
        ldlVal.isEmpty) {
      ToastUtils.toast("数据不能为空，请检查");
      return;
    }

    HttpData res = await ApiService().addServerFatData(data: {
      "patientUserId": uId,
      "patientInfoId": pId,
      "medicalAdviceId": mId,
      "value": resultVal,
      "evaluate": evaValue,
      "TC": tcVal,
      "TG": tgVal,
      "CE": ceVal,
      "HDL-C": hdlVal,
      "LDL-C": ldlVal
    });
    if (res.code == 1) {
      navToConsumable();
    } else {
      ToastUtils.toast("${res.msg}");
    }
  }

  // 添加其他服务数据
  void addOtherData() async {
    String uId = mpatientInfo.value.consumerId!.toString();
    String pId = mpatientInfo.value.id.toString();
    String mId = mserviceInfo.value.medicalAdviceId.toString();
    String enName = nameEnStr.value;
    String imgUrl = otherImgUrl.value;
    String result = OtherIntroController.text;
    String eva = otherElaController.text;
    if (uId.isEmpty || pId.isEmpty) {
      ToastUtils.toast("用户Id不能为空");
      return;
    }
    if (enName.isEmpty) {
      ToastUtils.toast("服务项名称不能为空");
      return;
    }
    if (imgUrl.isEmpty || result.isEmpty || eva.isEmpty) {
      ToastUtils.toast("数据不能为空，请检查后提交");
      return;
    }
    HttpData res =
        await ApiService().addServerOthertData(checkName: enName, data: {
      "patientUserId": uId,
      "patientInfoId": pId,
      "medicalAdviceId": mId,
      "evaluate": eva,
      "result": result,
      "resultImg": imgUrl
    });
    if (res.code == 1) {
      navToConsumable();
    } else {
      ToastUtils.toast("${res.msg}");
    }
  }

  /// 添加其他选项数据
  void showSelectImg() {
    BottomImagePickerTool.showBottomSheet(
        onCamera: () => getCameraImgs(), onGallery: () => getImgs());
  }

  /// 相机拍照
  getCameraImgs() async {
    XFile? _image;
    final picker = ImagePicker();
    _image = await picker.pickImage(source: ImageSource.camera);
    otherImgUrl.value = await uploadSingleFile(_image!.path);
  }

  /// 选择相册图片
  getImgs() async {
    XFile? _image;
    final picker = ImagePicker();
    _image = await picker.pickImage(source: ImageSource.gallery);
    otherImgUrl.value = await uploadSingleFile(_image!.path);
  }

  /// 单个图片上传
  Future<String> uploadSingleFile(String path) async {
    String userId = globalGetx.doctorInfo!.userId!;
    UploadData res = await ApiService()
        .uploadSingle( params: {
      "file": await MultipartFile.fromFile(path),
      "domain": 'fw/${userId}',
    });
    if (res.errCode == 0) {
      return res.uri!;
    }
    return '';
  }

  /// 更新服务包状态
  void updateServerStatus() async {
    HttpData res = await ApiService().updateServerStatus(data: {
      "patientNo": pNo.value,
      "servicePackageId": serviceId.value,
      "teamNo": tNo.value,
      "doctorNo": dNo.value,
      "checkId": cId.value,
      "serviceTime": mserviceInfo.value.serviceTime ?? ''
    });
    if (res.code == 1) {
      ToastUtils.toast("更新成功");
      getServerDetail(
          pNo: pNo.value,
          tNo: tNo.value,
          dNo: dNo.value,
          cId: cId.value,
          serviceId: serviceId.value);
    }
  }




  /// 跳转到添加耗材
  navToConsumable() {
    Get.toNamed(AppRoutes.consumables,
        arguments: {"patientNo": pNo.value, "checkId": cId.value})!.then((value) {
         getServerDetail(
          pNo: pNo.value,
          tNo: tNo.value,
          dNo: dNo.value,
          cId: cId.value,
          serviceId: serviceId.value);
        }
        );
  }
}
